from rest_framework import serializers
from rest_framework.serializers import ModelSerializer

from .models import User, Clazz


class ClazzSerializer(serializers.ModelSerializer):
    class Meta:
        model = Clazz
        fields = '__all__'


class UserSerializer(serializers.ModelSerializer):
    """
    用于用户查询结果的序列化
    """
    clazz = ClazzSerializer(read_only=True)

    class Meta:
        model = User
        # # fields = "__all__"
        # # 除密码外都序列化
        # exclude = ["password", "groups", "user_permissions"]
        fields = ['username', 'password', 'first_name', 'is_staff', 'clazz']
        extra_kwargs = {
            'password': {'write_only': True},
        }

    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        return user


# class UserFormSerializer(serializers.ModelSerializer):
#     username = serializers.CharField(required=False)
#
#     class Meta:
#         model = User
#         fields = "__all__"
#
#     def create(self, validated_data):
#         """
#         validated_data校验成功后的表单是一个字段
#         :param validated_data:
#         :return:
#         """
#         validated_data.pop("groups")
#         validated_data.pop("user_permissions")
#         return self.Meta.model.objects.create_user(**validated_data)
#
#     def update(self, instance, validated_data):
#         password = validated_data.pop("password", None)
#         # 设置密码
#         if password is not None:
#             instance.set_password(password)
#
#         return super().update(instance, validated_data)


# class ClazzAndUserSerializer(serializers.ModelSerializer):
#     users = UserSerializer(many=True, read_only=True)
#
#     class Meta:
#         model = Clazz
#         fields = "__all__"
